
import Foundation
import SwiftyJSON
//import Alamofire



class ListCallbackArgs {
    var ret:Int = -1
    var list:AnyObject = []
    var binary:[UInt8]?
}
typealias ListFilesCallback = (args : ListCallbackArgs)->()


class DeleteFileCallback{
    var ret:Int = -1
}
typealias DeleteFilesCallback = (args : DeleteFileCallback)->()

protocol DownloadFileCallback{
    func onSuccess(stream:NSData)
    func onFailure()
}
public class OSSManager {
    let  TAG = "OSSManager"
    let SHARE_DIR = "share"
    let PUBLIC_UID = "10000"
    static let DOWN_URL = "http://share.720vpai.com"

    //let ENDPOINT = "http://download-720vpai-com.oss-us-west-1.aliyuncs.com"
    let ENDPOINT = "http://share.720vpai.com"
    let BUCKET_NAME = "share-720vpai-com"
    let SIGN_URL="https://api.720vpai.com/upgrade/sign?content="
   // var client:OSSClient?
   // var provider:OSSCustomSignerCredentialProvider?

    let plainTextAccessKey = ""
    let secretKey = ""

    init(){
        initOSSClient()
    }
    
    //单例模式
    class var shareInstance : OSSManager{
        struct Static {
            static var instance: OSSManager?
            static var token: dispatch_once_t = 0
        }
        
        dispatch_once(&Static.token){
            Static.instance = OSSManager()
        }
        
        return Static.instance!
    }
    
    static func certificateWithFileName(fileName: String) -> SecCertificate {
        class Bundle {}
        //let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
        let filePath = NSBundle.mainBundle().pathForResource(fileName, ofType: "cer", inDirectory: "Music.bundle")!
        let data = NSData(contentsOfFile: filePath)!
        let certificate = SecCertificateCreateWithData(nil, data)!
        
        return certificate
    }
    
    static func getDownloadPath(path:String)->String{
        return "\(DOWN_URL)/\(path)"
    }
    func getSignature(content:String)->String?{
        //let query = content.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
        //trustedCertificates += [OSSManager.certificateWithFileName("server")]
//        
//        let path = "\(SIGN_URL)\(content)"
//       // if let result = NetUtil.requestHttps(path){
//            let json = SwiftyJSON.JSON.parse(result)
//            if json["ret"].int ?? -1 == 0 {
//                return json["signature"].string ?? ""
//            }
//        }else{
//            Log.info(self.TAG, msg: "getSignature error path = \(path) query:\(path)")
//        }
        return nil
    }
    
    func initOSSClient(){
        weak var weakself = self
        
//        Log.info(self.TAG, msg: "1 getSignature")
//        let credential = OSSCustomSignerCredentialProvider { (contentToSign, error) -> String! in
//            Log.info(self.TAG, msg: "2 getSignature:\(weakself?.getSignature(contentToSign))")
//            return weakself?.getSignature(contentToSign)
//        }
//        
//        Log.info(self.TAG, msg: "3 getSignature")
//        client = OSSClient(endpoint: ENDPOINT, credentialProvider: credential)
    }
    
    
//    func uploadFile(uid:String, file:UploadFile, newfilename:String,callback:UploadCallback?){
//     let put  = OSSPutObjectRequest()
//        put.bucketName = BUCKET_NAME
//        put.objectKey = getServerSharePath(uid, filename: newfilename)
//        put.uploadingFileURL = NSURL(fileURLWithPath: file.filename)
//        Log.info(self.TAG, msg: "getServerSharePath:\(put.objectKey)")
//        put.uploadProgress = {
//            bytesSent, totalBytesSent, totalBytesExpectedToSend in
//            callback?.onUploadStatus(file, type:UploadCallbackType.UPLOAD, value: Int(totalBytesSent*100/totalBytesExpectedToSend), postid: 0)
//                Log.info(self.TAG, msg: "uploadProgress:\(bytesSent) \(totalBytesSent) \(totalBytesExpectedToSend)")
//        }
//        let putTask = client?.putObject(put)
//        putTask?.continueWithBlock({ (task) -> AnyObject? in
//            if (task.error == nil) {
//                let result = task.result as! OSSPutObjectResult
//                Log.info(self.TAG, msg: "put:\(result.serverReturnJsonString)")
//            }else{
//                
//            }
//            file.filename = put.objectKey
//            callback?.onUploadStatus(file, type:UploadCallbackType.UPLOAD, value: 100, postid: 1)
//            return nil
//        })
//    }
//
//    func getServerSharePath(uid:String, filename:String)->String{
//        Log.info(self.TAG, msg: "filename:\(filename)")
//        return "media/\(uid)/\(filename)"
//    }

    static func newRandFileName(filepath:String, rand:Int64)->String{
        let names = filepath.characters.split("/").map(String.init)
        if names.count < 1{
            return filepath
        }
        let filename = names[names.count-1]
        let arrayString = filename.characters.split(".").map(String.init)
        if(arrayString.count < 2){
            return filename
        }else{
            return "\(arrayString[0])-\(rand).\(arrayString[1])"
        }
    }
    
    func getFileList(uid:String, callback:ListFilesCallback){
//        let listObjects = OSSGetBucketRequest()
//        listObjects.bucketName = BUCKET_NAME
//        listObjects.prefix = "media/\(uid)/"//"\(SHARE_DIR)/\(PUBLIC_UID)/"
//        let getTask = client?.getBucket(listObjects)
//        
//        //Log.info(self.TAG, msg: "getFileList:\(listObjects.prefix)")
//        getTask?.continueWithBlock({ (task) -> AnyObject? in
//            let args =  ListCallbackArgs()
//            if (task.error == nil) {
//                let result = task.result as! OSSGetBucketResult
//                args.ret = 0
//                if result.contents != nil {
//                    args.list = result.contents
//                }
//                //Log.info(self.TAG, msg: "OSSGetObjectResult length:\(args.list)")
//            }else{
//                args.ret = -1
//                Log.info(self.TAG, msg: "getFileList error")
//            }
//            callback(args: args)
//            return nil
//        })
    }


    func deleteFileAsync(serverfile:String,  callback:DeleteFilesCallback){
//        let delete = OSSDeleteObjectRequest()
//        delete.bucketName = BUCKET_NAME
//        let webpath = OSSManager.DOWN_URL + "/"
//        if !serverfile.containsString(webpath){
//            callback(args: DeleteFileCallback())
//            return
//        }
//        delete.objectKey = serverfile.substringFromIndex(webpath.endIndex)
//        let deleteTask = client?.deleteObject(delete)
//        deleteTask?.continueWithBlock({ (task) -> AnyObject? in
//            let args =  DeleteFileCallback()
//            if (task.error == nil) {
//                args.ret = 0
//                Log.info(self.TAG, msg: "OSSDeleteObjectResult:\(delete.objectKey)")
//            }else{
//                Log.info(self.TAG, msg: "error  OSSDeleteObjectResult:\(delete.objectKey)")
//            }
//            callback(args: args)
//            return nil
//        })
    }


    func downloadFile(serverfile:String, callback:DownloadFileCallback){
//        let get = OSSGetObjectRequest()
//        get.bucketName = BUCKET_NAME
//        get.objectKey = serverfile
//        let getTask = client?.getObject(get)
//        getTask?.continueWithBlock({ (task) -> AnyObject? in
//            if (task.error == nil) {
//                let result = task.result as! OSSGetObjectResult
//                Log.info(self.TAG, msg: "OSSGetObjectResult:\(result)")
//            }else{
//                
//            }
//            return nil
//        })
    }

}
